package role

import (
	"context"
	"strings"
	"time"

	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateRoleLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateRoleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateRoleLogic {
	return &CreateRoleLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *CreateRoleLogic) CreateRole(in *backend.RoleInfo) (*backend.BaseIDResp, error) {
	var role model.SysRole
	if in.Name != nil {
		role.Name = strings.TrimSpace(*in.Name)

		if len(role.Name) == 0 {
			return nil, errorx.NewInvalidArgumentError("role.nameRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysRoleColumns.Name] = map[string][]any{
			"equalTo": []any{role.Name},
		}
		_, count, err := l.svcCtx.SysRole.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("role.nameAlreadyExists")
		}
	}
	if in.Code != nil {
		role.Code = strings.TrimSpace(*in.Code)

		if len(role.Code) == 0 {
			logx.Errorw("create role failed, its code is required")
			return nil, errorx.NewInvalidArgumentError("role.codeRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.SysRoleColumns.Code] = map[string][]any{
			"equalTo": []any{role.Code},
		}
		_, count, err := l.svcCtx.SysRole.GetList(l.ctx, model.M{}, 0, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if count > 0 {
			return nil, errorx.NewAlreadyExistsError("role.codeAlreadyExists")
		}
	}
	if in.Sort != nil {
		role.Sort = uint16(*in.Sort)
	}
	if in.Status != nil {
		role.Status = uint8(*in.Status)
	}
	if in.Remark != nil {
		role.Remark = strings.TrimSpace(*in.Remark)
	}
	if in.DefaultRouter != nil {
		role.DefaultRouter = strings.TrimSpace(*in.DefaultRouter)
	}
	role.CreatedAt = time.Now()
	role.UpdatedAt = time.Now()
	err := l.svcCtx.SysRole.Insert(l.ctx, nil, &role)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	return &backend.BaseIDResp{
		Id:  role.ID,
		Msg: i18n.CreateSuccess,
	}, nil
}
